class Server
{
    constructor ()
    {
        this.requestRouterSetTimeOut = null;
    }
    // static intervalHandle = 10;
     static getInstance()
     {
         if(!Server.instance){
             Server.instance = new Server();
         }
         return Server.instance;
     }

    /**
     * 更新到服务器
     * 需要满足两个条件
     *   1)OBJECT.routerPonits[routerId].UpdateStatus ==false
     *   2)OBJECT.routerPonits[routerId].driverId  不为空
     *   加上 第一个起点（后仓）和最后一个点（司机家或者货仓）
     */
    updateRouters(routerId){
        return new Promise( (resolve ,reject)=>{
          let routerPonts = OBJECT.routerPonits[routerId];
          if( typeof routerPonts.driverId != 'undefined' &&  routerPonts.driverId )
          {
                  let updateJson = {};
                  let distanceAndTime = assignRoute.getInstance().calcDistanceAndTimes( routerId );   //总距离和时间
                  updateJson.weight = assignRoute.getInstance().calcLbs( routerPonts.points );
                  updateJson.stops = routerPonts.points.length
                  updateJson.hours = distanceAndTime.time;
                  updateJson.distance = distanceAndTime.distance;
                  updateJson.vehicle_id =  routerPonts.vehicleId;
                  updateJson.driver_id =  routerPonts.driverId;
                  updateJson.schedule = routerPonts.schedule;
                  updateJson.routers = routerPonts.points;
                  updateJson.title   = OBJECT.routersNameMap[routerId];
                  updateJson.warehouse = CONFIG.wareHouseCode;
                  updateJson.router_edge_points = OBJECT.routerEdgePoints[routerId];
                  //添加第一个起点
                  updateJson.start_location = `{"lat":${CONFIG.wareHouseCenter.lat},"lng":${CONFIG.wareHouseCenter.lng}}`;
                  let lastPoints = Driver.getInstance().getLastPoint( routerId );
                  updateJson.end_location =`{"lat":${lastPoints.lat},"lng":${lastPoints.lng}}`;
                  this.submintToServer(routerId ,updateJson,resolve,reject);
                //  OBJECT.routerPonits[key].UpdateStatus = true;
          }
          resolve('SUCCESS');
        })

    }
    /**
     * 是否超过三个点
     * @param routers
     */
    isOverFourPoints(routers)
    {
        return routers.length >=3;
    }
    /**
     * 把每个点放到对应的多边形
     */
    assignPointToPolygon(routerId)
    {

            return new Promise( ( resolve , reject)=>{

              let polygon = OBJECT.routerEdgePoints[routerId];
              let temp = [];
              let oldRouterPonits =[];
              OBJECT.routerPonits[routerId]= OBJECT.routerPonits[routerId] || [];
               oldRouterPonits = (typeof OBJECT.routerPonits[routerId].points == 'undefined') ? [] : OBJECT.routerPonits[routerId].points;
              OBJECT.routerPonits[routerId].points =[];
              for(let CustID in  OBJECT.customerPositionList)
              {

                  if(Polygon.isInArea({lat:OBJECT.customerPositionList[CustID].lat,lng:OBJECT.customerPositionList[CustID].lng}, polygon))
                  {
                      temp.push( OBJECT.customerPositionList[CustID] )
                  }
              }
              if(temp.length >=23 )
              {
                  $.Pro('最大不能超过23个点');
                  reject('FAIL NOT OVER 23 POINTS');
                  colseLoading();
                  return false;
              }
                /**
                 * 有可能出现以下这些情况
                 *  1.拖动列表顺序的但是Router的waypoints数量是没有变化的 这时候不用重新push 因为push了顺序相当于重新排序了
                 */
                if( CONFIG.optimizeOrderpoints[routerId] )
                {

                    OBJECT.routerPonits[routerId].points=temp;
                }else if(oldRouterPonits){

                    OBJECT.routerPonits[routerId].points=oldRouterPonits;
                }else{

                    OBJECT.routerPonits[routerId].points=temp;
                }

                resolve('SUCCESS');
            })
    }
    /**
     * 更新数据到服务器
     * @param routerId
     * @param data
     */
    submintToServer( routerId , data ,resolve,reject){
        let post ={
            id:routerId,
            weight:data.weight,
            stops:data.stops,
            hours:data.hours,
            vehicle_id:data.vehicle_id,
            distance:data.distance,
            routers:JSON.stringify(data.routers),
            schedule:JSON.stringify(data.schedule),
            driver_id:data.driver_id,
            title:data.title,
            warehouse:data.warehouse,
            start_location:data.start_location,
            end_location:data.end_location,
            router_edge_points:JSON.stringify( data.router_edge_points )
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: CONFIG.updateRouterUrl ,
            data: post,
            success: function (result) {
                resolve('SUCCESS')
            },
            error : function() {
                reject('error :Server=>submintToServer  ')
            }
        });
    }

    /**
     * 批量请求Directions Service API
     */
    requestRouter()
    {
        this.requestRouterSetTimeOut = setTimeout(()=>{
             let len = OBJECT.requestRoutePromiseHandle.length;
             if(len)
             {
                 if( OBJECT.requestRoutePromiseHandle[0].locked === false && (typeof OBJECT.requestRoutePromiseHandle[0].points !='undefined'))
                 {
                     OBJECT.requestRoutePromiseHandle[0].locked = true;          //设置当前任务为锁定状态
                     let task = OBJECT.requestRoutePromiseHandle[0];
                     new Promise( function ( resovle , reject) {
                        Router.getInstance().calculateRoute( task.points , task.routerId , task.color ,resovle , reject );
                     }).then( function (value) {
                         OBJECT.requestRoutePromiseHandle.shift();
                         Server.getInstance().requestRouter();
                     },function (error) {
                         console.log('Route Request Fail:'+error);
                     })
                 }
                 showLoading();
             }else{
                 this.requestRouter();
                 colseLoading();
             }
         },500)
    }



}
